<?php
// $Id$

/**
 * Controller_Admin_Cdr 控制器
 */
class Controller_Admin_Cdr extends Controller_Abstract
{

	function _format_appendSql()
	{
		if (isset($_SESSION['acct']))
		{
			if ($_SESSION['acct']['admin_id'] == -1 && $_SESSION['acct']['agent_id'] == -1)
			{
			//为管理
				//$append['']
				$append['admin_id'] = $_SESSION['acct']['id'];
				
			}else
			{
				$append['admin_id'] = $_SESSION['acct']['admin_id'];
				$append['agent_id'] = Acct::_get_have_acctid($_SESSION['acct']['id'], $_SESSION['acct']['admin_id']);
				$append['agent_id'][] = $_SESSION['acct']['id'];
			}
		}
		return $append;
	}
	
	function actionoutput()
	{
		$sql = ($_SESSION['lastsql']);
		$obj = Cdr::find($sql);
		$data = $obj->setColumns('agent_id,caller_id_number, destination_number, start_stamp, answer_stamp, end_stamp, billsec,costuser,costagent')->asArray()->getAll();
		
		//$sql = "";
		//$param['id'] = $this->_context->ids;
		//$data = Vouchercard::find($cond)->setColumns('cardname, password, balance, expireddays, activedate, expireddate, voucher_acctname')->asArray()->getAll();
		if (count($data))
		{
			$header = array('代理ID','帐号','被叫','开始','应答','结束','时长','用户费','代理费');
			$data = array_merge(array($header),$data);				
		}
		
		$output = new Helper_dboutput($data);
		$output->output_txt();
	}
	//话费详单
	function actionhistroy()
	{
		$agent_id = intval($this->_context->agent_id);
		$dstchannel = trim($this->_context->dstchannel);
		$start_date = trim($this->_context->start_date);
		$end_date = trim($this->_context->end_date);
		$end_date = date('Y-m-d',strtotime($end_date)+86400);
		$caller_id_number = trim($this->_context->caller_id_number);
		$destination_number = trim($this->_context->destination_number);
		if ($start_date)
		{
			$split = explode('-', $start_date);
			$yeah = $split[0];
			$month = $split[1];
		}else
		{
			$yeah = date('Y',time());
			$month = sprintf('%02d',date('m',time()));
		}
		$_SESSION['cdr_yeah'] = $yeah;
		$_SESSION['cdr_month'] = $month;
		$where = "1 = 1";
		if($agent_id)
		{
			$where .= " AND agent_id = {$agent_id}";
		}
		if($dstchannel)
		{
			$where .= " AND dstchannel like '%{$dstchannel}%'";
		}
		if($start_date)
		{
			$where .= " AND start_stamp >= '{$start_date}'";
		}
		if($end_date)
		{
			$where .= " AND start_stamp < '{$end_date}'";
		}
		if($caller_id_number)
		{
			$where .= " AND caller_id_number like '%{$caller_id_number}%'";
		}
		if($destination_number)
		{
			$where .= " AND destination_number like '%{$destination_number}%'";
		}
		if($_SESSION['acct']['acclevel'] == 3)
		{
			$where .= " AND caller_id_number = ".$_SESSION['acct']['acctname'];
		}else if($_SESSION['acct']['acclevel'] == 2){
			$append['agent_id'] = Acct::_get_have_acctid($_SESSION['acct']['id'], $_SESSION['acct']['admin_id']);
			$append['agent_id'][] = $_SESSION['acct']['id'];
			$agent_ids = implode(',', $append['agent_id']);
			$where .= " AND agent_id in ({$agent_ids})";
		}
		$_SESSION['lastsql'] = $where;
		$pagination = null;
		//获取搜索参数
		$this->get_param();
		//初始化分页信息
		$this->_format_page_info();
		//$costgateway = Cdr::find($where)->getSum('costgateway');
		//$this->_view['costgateway'] = $costgateway;
		$costagent = Cdr::find($where)->getSum('costagent');
		$this->_view['costagent'] = $costagent;
		$costuser = Cdr::find($where)->getSum('costuser');
		$this->_view['costuser'] = $costuser;
		$usercount = Cdr::find($where)->distinct(true)->getCount('caller_id_number');
		$this->_view['usercount'] = $usercount;
		$item = Cdr::find($where)->limitPage($this->curr_page,$this->page_size)->fetchPagination($pagination)->order('id desc')->getAll();
		$this->_view['item'] = $item;
		$this->_view['pagination'] = $pagination;
		$this->_view['agent_list'] = Acct::_get_arrayinfo($this->_format_appendSql());
	}
	function actioncosthistroy()
	{
		if (isset($this->_context->_yeah) && isset($this->_context->_month))
		{
			$yeah = ($this->_context->_yeah);
			$month = ($this->_context->_month);
		}else
		{
			$yeah = date('Y',time());
			$month = sprintf('%02d',date('m',time()));
		}
		$start_day = intval($this->_context->begin_day);
		$end_day = intval($this->_context->end_day);
		$end_day = date('Y-m-d',strtotime($end_day)+86400);
		$agent_id = intval($this->_context->agent_id);
		
		$result = array();
		if ($agent_id > 0 )
		{
			$acct = Acct::find('id = ?',$agent_id)->getOne();
			if ($acct->acctname)
			{
				$param['agent_id'] = $agent_id;
				$param['admin_id'] = Acct::cur_admin_id();
				if($start_day > $end_day){$end_day = $start_day;}
				//$query = Cdr::find(' agent_id = ? and admin_id = ? and (start_stamp >= ? and start_stamp <= ? )',$agent_id,Acct::cur_admin_id(),sprintf('%d-%d-%d 00-00-00',$yeah,$month,$start_day),sprintf('%d-%d-%d 23:59:59',$yeah,$month,$end_day))->getall();
				$query = sprintf('agent_id = %d and admin_id = %d and (start_stamp >= \'%s\' and start_stamp <= \'%s\' )',$agent_id,Acct::cur_admin_id(),sprintf('%d-%d-%d 00-00-00',$yeah,$month,$start_day),sprintf('%d-%d-%d 23:59:59',$yeah,$month,$end_day));
				$sql = "select SUM(costuser) AS sum_costuser,SUM(billsec) AS sum_billsec,accountcode as user_acctname from ".Cdr::meta()->table->name." where ".$query." group by accountcode";
				
				$fetch = QDB::getConn()->execute($sql)->fetchAll();
				
				$i = 0;
				foreach ($fetch as $rows)
				{
					
					$result[$i]['acctname'] = $acct->acctname;
					$result[$i]['datetime'] = sprintf('%d/%d/%d-%d',$yeah,$month,$start_day,$end_day);
					$acctuser = Acctuser::find('acctname = ?',$rows['user_acctname'])->setColumns('id,acctname,balance')->getOne();
					$result[$i]['balance'] = $acctuser->balance?$acctuser->balance:0;
					$result[$i] = array_merge($result[$i],$rows);
					
					$i+=1;
				}
				//var_dump($result);
			}
		}
		
		
		$this->_view['result'] = $result;
		$this->_view['agent_list'] = Acct::_get_arrayinfo($this->_format_appendSql());
	}
	function actionsmsmsg()
	{
		$this->union_table = Smscdr::meta();
		if($_SESSION['acct']['acclevel'] == 3)
		{
				$this->lists(array('user_acctname'=>$_SESSION['acct']['acctname']));
		}else{
				$this->lists($this->_format_appendSql());
				$this->_view['agent_list'] = Acct::_get_arrayinfo($this->_format_appendSql());	
		}
	}
	
	function actionlistcost()
	{
		$start_date = ($this->_context->start_date)?trim($this->_context->start_date):date('Y-m-d');
		$end_date = ($this->_context->end_date) ? trim($this->_context->end_date) : date('Y-m-d',strtotime('+1 day'));
		$end_date = date('Y-m-d',strtotime($end_date));
		$secnum = ($this->_context->secnum) ? intval($this->_context->secnum) : 6;
		if ($start_date)
		{
			$split = explode('-', $start_date);
			$yeah = $split[0];
			$month = $split[1];
		}else
		{
			$yeah = date('Y',time());
			$month = sprintf('%02d',date('m',time()));
		}
		if(strtotime("$yeah-$month") > time())
		{
			exit('超出日期');
		}
		$_SESSION['cdr_yeah'] = $yeah;
		$_SESSION['cdr_month'] = $month;
		
			$where = " start_stamp >= '{$start_date}' and start_stamp < '{$end_date} 23:59:59'";
			$acct = Acct::find('agent_id = ?',$_SESSION['acct']['id'])->setColumns('id')->asArray()->getAll();
			$acctarr = Helper_Array::toHashmap($acct, 'id','id');
// 			if($_SESSION['acct']['acclevel'] == 0)
// 			{
// 				$where .= ' and admin_id = '.$_SESSION['acct']['id']; 
// 			}else
// 			{
				$userWhere = $where.' and agent_id = '.$_SESSION['acct']['id'];
				if(count($acctarr))
				{
					$append['agent_id'] = $acctarr;
				}else{
					$append['agent_id'] = array(0);
				}
				$array = array();
				foreach ($append['agent_id'] as $_k=>$_v)
				{
					$array[] = ' agent_id = '.$_v.' ';
				}
				$where .= ' and ('. implode(' OR ', $array) .')';
				//$append['agent_id'][] = $_SESSION['acct']['id'];
				//$where .= " and  agent_id in (".implode(',', $append['agent_id']).')';
			//}
				
		$this->get_param();		
		$sql = "select agent_id,sum(billsec) as billsec,sum(ceil(billsec/{$secnum})) as secnum,sum(cost) as cost,sum(fees) as fees from ".Cost::meta()->table->name." where {$where} group by agent_id";
		
		$data = QDB::getConn()->getAll($sql);
// 		$countsql = "select sum(billsec) as billsec,sum(ceil(billsec/{$secnum})) as secnum,sum(cost) as cost,sum(fees) as fees from ".Cost::meta()->table->name." where {$where}";
// 		$count = QDB::getConn()->getAll($countsql);
		#user利润
		$usersql = "select {$_SESSION['acct']['id']} as agent_id,sum(billsec) as billsec,sum(ceil(billsec/{$secnum})) as secnum,sum(costagent) as cost,sum(costuser) as fees from ".cdr::meta()->table->name." where {$userWhere}";
		$users = QDB::getConn()->getAll($usersql);
		$packagemoney = Userpackagelog::find('agent_id = ? and created>= ? and created<?',$_SESSION['acct']['id'],strtotime($start_date),strtotime($end_date." 23:59:59"))->getSum('debit','totalmoney');
		$this->_view['packagemoney'] = $packagemoney;
		if(isset($users[0]['billsec']))
		{
			$me = $users;
		}else{
			$me[] = array(
						'agent_id'=>$_SESSION['acct']['id'],
						'billsec'=>0,
						'secnum'=>0,
						'cost'=>0,
						'fees'=>0
					);
		}
		$data = array_merge($me,$data);
		
		
		if(!isset($count[0]['billsec']))
		{
			$count[] = array(
						'billsec'=>0,
						'secnum'=>0,
						'cost'=>0,
						'fees'=>0
					);
		}
		$count[0]['billsec'] = array_sum(Helper_Array::getCols($data, 'billsec'));
		$count[0]['secnum'] = array_sum(Helper_Array::getCols($data, 'secnum'));
		$count[0]['cost'] = array_sum(Helper_Array::getCols($data, 'cost'));
		$count[0]['fees'] = array_sum(Helper_Array::getCols($data, 'fees'));
		

		
		$this->_view['count'] = $count;
// 		$start_day = ($this->_context->begin_day);
// 		$end_day = ($this->_context->end_day);
// 		$agent_id = isset($this->_context->agent_id)?intval($this->_context->agent_id):$_SESSION['acct']['id'];
// 		$param = $this->_format_appendSql();
// 		if(isset($param['agent_id']) && !in_array($agent_id, $param['agent_id']))
// 		{
// 			exit('请勿尝试');
// 		}
		
// 		$start_day = $start_day  ?  $start_day : date('d',time()) ;
// 		$end_day = $end_day  ?  $end_day : date('d',time() + 86400) ;
		
		
		
// 		$postdata = array(
// 			'years'=>$yeah,
// 			'month'=>$month,
// 			'agent_id'=>$agent_id,
// 			'begin_day'=>$start_day,
// 			'end_day'=>$end_day,
// 			'billsec_count'=>6,
// 			'agent_acctname'=>''
// 		);
		
		
// 		$rows = Cost::callhistory_list_cost($postdata);
		
		
 		$this->_view['data'] = $data;
// 		$this->_view['agent_list'] = Acct::_get_arrayinfo($this->_format_appendSql());
 		$this->_view['start_day'] = strtotime("$start_date");
 		$this->_view['end_day'] = strtotime("$end_date");
		
	}
}


